package com.awei.study.design.structure.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Author liweilong
 * @Date 2024/8/2 16:41
 * 动态代理——JDK代理
 */
public class JdkProxy {
    public interface SellWindows{
        void sell();
        void sell1();
    }

    public static class TrainSell implements SellWindows {

        @Override
        public void sell() {
            System.out.println("火车站售票");
        }

        @Override
        public void sell1() {
            System.out.println("火车站售票1");
        }
    }


    public static class ProxyFactory {
        private TrainSell trainSell = new TrainSell();

        public SellWindows getProxyObject () {
            SellWindows sellWindows = (SellWindows) Proxy.newProxyInstance(trainSell.getClass().getClassLoader(), trainSell.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("收取中介费用");
                    Object invoke = method.invoke(trainSell, args);
                    return invoke;
                }
            });
            return sellWindows;
        }
    }

    public static void main(String[] args) {
        ProxyFactory proxyFactory = new ProxyFactory();
        SellWindows object = proxyFactory.getProxyObject();
        object.sell();
        object.sell1();
    }
}
